/**
 * User: alesj
 * Date: 2005.2.23
 * Time: 13:19:04
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.generalynx.common.web.tags;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

public abstract class CommonWriteTag extends TagSupport implements IRootable {

    //dummy condition plugin
    private static final ITagOutputConditionPlugin DUMMY = new DummyTagOutputConditionPlugin();

    //output condition plugin
    /**
     * Do we even print current node, if its collection is empty.
     * Before we must register plugin with plugin interceptor - see ecos-servlet.xml.
     */
    private String outputConditionPluginName;

    protected ITagOutputConditionPlugin conditionPlugin = DUMMY;

    public int getLevel() {
        Tag parentTag = getParent();
        if (parentTag == null || !(parentTag instanceof IRootable)) {
            return 0;
        } else {
            return ((IRootable)parentTag).getLevel() + 1;
        }
    }

    public ITagOutputConditionPlugin getConditionPlugin() {
        return conditionPlugin;
    }

    protected void write(String output) throws JspException {
        try {
            JspWriter writer = pageContext.getOut();
            writer.write(output);
        } catch (IOException e) {
            throw new JspException(e.getMessage());
        }
    }

    /**
     * Do not have to check if plugin is null.
     */
    private static class DummyTagOutputConditionPlugin implements ITagOutputConditionPlugin {
        public boolean outputNode(Object node) {
            return true;
        }
    }

    // -------------------------------------------------------------------------- //

    public String getOutputConditionPluginName() {
        return outputConditionPluginName;
    }

    public void setOutputConditionPluginName(String outputConditionPluginName) {
        this.outputConditionPluginName = outputConditionPluginName;
    }
}
